<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="queryParams.title" placeholder="请输入文章标题" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
            <el-option label="四季养生" value="四季养生" />
            <el-option label="饮食调养" value="饮食调养" />
            <el-option label="运动保健" value="运动保健" />
            <el-option label="睡眠养生" value="睡眠养生" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="queryParams.tag" placeholder="请选择标签" clearable>
            <el-option label="春季" value="春季" />
            <el-option label="夏季" value="夏季" />
            <el-option label="秋季" value="秋季" />
            <el-option label="冬季" value="冬季" />
            <el-option label="养生" value="养生" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-container">
      <el-button type="primary" @click="handleAdd">发布文章</el-button>
      <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="articleList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="文章标题" prop="title" min-width="200" show-overflow-tooltip />
      <el-table-column label="分类" prop="category" width="120" align="center" />
      <el-table-column label="标签" width="160">
        <template #default="{ row }">
          <el-tag v-for="tag in row.tags" :key="tag" style="margin-right: 5px">{{ tag }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="阅读量" prop="readCount" width="100" align="center" />
      <el-table-column label="发布状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '已发布' : '草稿' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" prop="publishTime" width="160" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button type="text" @click="handlePreview(row)">预览</el-button>
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" style="color: #f56c6c" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑文章对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      destroy-on-close
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="articleFormRef"
        :model="articleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="文章分类" prop="category">
          <el-select v-model="articleForm.category" placeholder="请选择分类" style="width: 100%">
            <el-option label="四季养生" value="四季养生" />
            <el-option label="饮食调养" value="饮食调养" />
            <el-option label="运动保健" value="运动保健" />
            <el-option label="睡眠养生" value="睡眠养生" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签" prop="tags">
          <el-select
            v-model="articleForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择标签，可自定义输入"
            style="width: 100%"
          >
            <el-option label="春季" value="春季" />
            <el-option label="夏季" value="夏季" />
            <el-option label="秋季" value="秋季" />
            <el-option label="冬季" value="冬季" />
            <el-option label="养生" value="养生" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleCoverChange"
          >
            <img v-if="coverUrl" :src="coverUrl" class="cover-image" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章摘要" prop="summary">
          <el-input
            v-model="articleForm.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入文章摘要"
          />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor-container">
            <!-- 在实际应用中，这里应该是富文本编辑器组件 -->
            <el-input
              v-model="articleForm.content"
              type="textarea"
              :rows="15"
              placeholder="请输入文章内容"
            />
          </div>
        </el-form-item>
        <el-form-item label="发布状态">
          <el-radio-group v-model="articleForm.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 预览文章对话框 -->
    <el-dialog
      v-model="previewDialog.visible"
      title="文章预览"
      width="900px"
      append-to-body
    >
      <div class="article-preview">
        <h1 class="preview-title">{{ previewData.title }}</h1>
        <div class="preview-info">
          <span>分类：{{ previewData.category }}</span>
          <span>发布时间：{{ previewData.publishTime }}</span>
          <span>阅读量：{{ previewData.readCount }}</span>
        </div>
        <div class="preview-tags">
          <el-tag
            v-for="tag in previewData.tags"
            :key="tag"
            style="margin-right: 8px"
          >
            {{ tag }}
          </el-tag>
        </div>
        <div class="preview-cover" v-if="previewData.coverUrl">
          <img :src="previewData.coverUrl" alt="封面图" />
        </div>
        <div class="preview-summary">
          <p>{{ previewData.summary }}</p>
        </div>
        <div class="preview-content" v-html="previewData.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getArticleList, getArticleDetail, addArticle, updateArticle, deleteArticle } from '@/api/knowledge'

const loading = ref(false)
const articleList = ref([])
const total = ref(0)
const selectedIds = ref([])
const articleFormRef = ref()
const coverUrl = ref('')

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  category: '',
  tag: ''
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  tags: [{ required: true, message: '请选择文章标签', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}

// 对话框状态
const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

// 预览对话框状态
const previewDialog = reactive({
  visible: false
})

// 文章表单对象
const articleForm = reactive({
  id: undefined,
  title: '',
  category: '',
  tags: [],
  coverUrl: '',
  summary: '',
  content: '',
  status: 1
})

// 预览数据对象
const previewData = reactive({
  id: '',
  title: '',
  category: '',
  tags: [],
  coverUrl: '',
  summary: '',
  content: '',
  publishTime: '',
  readCount: 0
})

// 获取文章列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getArticleList(queryParams)
    articleList.value = res.data.rows
    total.value = res.data.total
  } catch (error) {
    console.error('获取文章列表失败', error)
  } finally {
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  getList()
})

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询条件
const resetQuery = () => {
  queryParams.title = ''
  queryParams.category = ''
  queryParams.tag = ''
  handleQuery()
}

// 表格选择行变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 每页数量变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

// 添加文章
const handleAdd = () => {
  resetForm()
  dialog.title = '发布文章'
  dialog.type = 'add'
  dialog.visible = true
}

// 编辑文章
const handleEdit = async (row) => {
  resetForm()
  dialog.title = '编辑文章'
  dialog.type = 'edit'
  dialog.visible = true
  
  const res = await getArticleDetail(row.id)
  Object.assign(articleForm, res.data)
  coverUrl.value = articleForm.coverUrl
}

// 预览文章
const handlePreview = async (row) => {
  const res = await getArticleDetail(row.id)
  Object.assign(previewData, res.data)
  previewDialog.visible = true
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除文章 "${row.title}" 吗？`, '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await deleteArticle(row.id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 批量删除文章
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条数据吗？`, '警告', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    await deleteArticle(selectedIds.value.join(','))
    ElMessage.success('批量删除成功')
    getList()
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  articleForm.id = undefined
  articleForm.title = ''
  articleForm.category = ''
  articleForm.tags = []
  articleForm.coverUrl = ''
  articleForm.summary = ''
  articleForm.content = ''
  articleForm.status = 1
  coverUrl.value = ''
}

// 处理封面图片上传
const handleCoverChange = (file) => {
  // 实际应用中需要调用上传API
  // 这里模拟上传成功后的行为
  const reader = new FileReader()
  reader.onload = (e) => {
    coverUrl.value = e.target.result
    articleForm.coverUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 提交表单
const submitForm = async () => {
  articleFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (dialog.type === 'add') {
        await addArticle(articleForm)
        ElMessage.success('发布成功')
      } else {
        await updateArticle(articleForm)
        ElMessage.success('修改成功')
      }
      
      dialog.visible = false
      getList()
    } catch (error) {
      console.error('保存失败', error)
    }
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .filter-container {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }
  
  .action-container {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
  
  .editor-container {
    min-height: 300px;
    margin-bottom: 20px;
  }
  
  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      line-height: 178px;
    }
    
    .cover-image {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  
  .article-preview {
    padding: 20px;
    
    .preview-title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 15px;
      text-align: center;
    }
    
    .preview-info {
      font-size: 14px;
      color: #666;
      margin-bottom: 15px;
      text-align: center;
      
      span {
        margin-right: 15px;
      }
    }
    
    .preview-tags {
      margin-bottom: 20px;
      text-align: center;
    }
    
    .preview-cover {
      text-align: center;
      margin-bottom: 20px;
      
      img {
        max-width: 100%;
        max-height: 300px;
      }
    }
    
    .preview-summary {
      background-color: #f8f8f8;
      padding: 10px;
      border-left: 4px solid #409eff;
      margin-bottom: 20px;
      font-style: italic;
    }
    
    .preview-content {
      line-height: 1.8;
    }
  }
}
</style> 